# 三、shell 流程控制语句
shell 脚本和其他大多数程序设计语言一样,为了实现更加复杂的功能,也有用于控制程序执行流程的“条件分支语句”
# test 条件测试
test 命令用来检查某个条件是否成立。执行条件测试操作以后,通过?页定义变量$? 获取测试命令的返回状态,返回值为 0 表示条件成立,返回值为 1 表示条件不成立。
# test 命令 文本测试常用参数:
选项 | 说明 |
---|---|
-d | 是否为目录 |
-f | 是否为文件 |
-r | 测试当前用户是否有读权限 |
-w | 测试当前用户是否有写权限 |
-x | 测试当前用户是否有执行权限 |
示例:
[root@192 ~]# test -d /root
[root@192 ~]# echo $?
0 #0表示条件成立
1
2
3
2
3
# test 命令 数值比较常用参数:
选项 | 说明 |
---|---|
-ne or != | 两数值不相等 |
-gt or > | num1 大于num2 |
-lt or < | num1 小于nurti2 |
-ge or >= | num1 大于等于 mm2 |
-le or <= | num1 小于等于 num2 |
示例:
[root@192 ~]# test 10 -eq 11
[root@192 ~]# echo $?
1 #10不小于1
1
2
3
2
3
# test 命令 字符串比较常用参数:
选项 | 说明 |
---|---|
-n | 两数值不相等 |
str1=str2 | 判断 str1 是否等于 str2, 若相等则返回 true |
str1!=str2 | 判断 str1 是否不等于 str2, 若相等则返回 false |
示例:
[root@192 ~]# cat str.sh
str1="aa"
str2="bb"
test $str1 = $str2 #注意变量之前的空格
echo $?
[root@192 ~]# sh str.sh
1 #两个字符串不相等
1
2
3
4
5
6
7
2
3
4
5
6
7
# if 语句
# 单分支 if
语句
单分支 if 语句是最常见的条件判断式。当 “条件成立”时,执行1相应的操作,否则不执行任何操作。
[root@192 ~]# cat if.sh
#!/bin/bash
read -p "please input the first num:" first
read -p "please input the second num:" second
if [ $first -gt $second ]
then
echo "$first > $second"
else
echo "$first <= $second"
fi
[root@192 ~]# sh if.sh
please input the first num:1
please input the second num:2
1 <= 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 多分支 elif
语句
多分支 if 语句相当于 if 语句嵌套,针对多个条件执行不同操作
[root@192 ~]# cat elif.sh
#!/bin/bash
read -p "请输入您的成绩(0-100):" score
if (($score >= 90)) && (($score <= 100))
then
echo "$score, 属于优秀档次!"
elif (($score < 90)) && (($score >= 80))
then
echo "$score, 属于良好档次!"
elif (($score < 80)) && (( $score >= 60))
then
echo "$score, 属于及格档次!"
else
echo "$score, 属于不及格档次!"
fi
[root@192 ~]# sh elif.sh
请输入您的成绩(0-100):85
85, 属于良好档次!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# case 语句
[root@192 ~]# cat case.sh
#!/bin/bash
read -p "please input your score:" score
case $score in
[9][0-9]|100)
echo "成绩:$score,等级为优秀!"
;;
[8][0-9])
echo "成绩:$score,等级为良好!"
;;
[6-7][0-9])
echo "成绩:$score,等级为中等!"
;;
[0-5][0-9])
echo "成绩:$score,等级为不及格!"
;;
*)
echo "成绩输入不合法:$score"
;;
esac
[root@192 ~]# sh case.sh
please input your score:99
成绩:99,等级为优秀!
[root@192 ~]# sh case.sh
please input your score:100^H1
成绩输入不合法:101
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# for 循环语句
for 循环语句对一个变量依次赋值后,重复执行同一个命令序列。
[root@192 ~]# cat for.sh
#!/bin/bash
for ((i=1;i<=20;i=i+1))
do
echo "i is $i"
done
[root@192 ~]# sh for.sh
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
i is 10
i is 11
i is 12
i is 13
i is 14
i is 15
i is 16
i is 17
i is 18
i is 19
i is 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
← 二、shell 变量 四、shell 方法 →